﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using QQ.Util;
using System.Threading;
using System.Diagnostics;
using RTGather.Lib.gather;
using RTGather.Lib;
using System.Text.RegularExpressions;

namespace BlogManager
{
    public partial class MainForm : Form
    {

        private string username = "";
        private string password = "";
        private string url = "";
        private string type = "";

        private  int count=0;

        private Rectangle dragBoxFromMouseDown;
        private int rowIndexFromMouseDown;
        private int rowIndexOfItemUnderMouseToDrop;

        /// <summary>
        /// 
        /// </summary>
        private int visitcount = 0;


        public MainForm()
        {
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; 
            InitializeComponent();
            LoadContent();
            this.data_blog.ContextMenuStrip = this.CreateContextMenu();
            this.data_blog.ContextMenuStrip.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.contextMenuStrip_ItemClicked);
            this.data_blog.ContextMenuStrip.Paint += new System.Windows.Forms.PaintEventHandler(this.contextMenuStrip_Paint);
        }


        public void LoadContent()
        {
            foreach (Blog b in ConfigXML.Content)
            {
                string[] row = { b.blogType, b.blogTitle,b.blogKeyword, b.blogUsername, b.blogPassowod, b.blogUrl,b.blogDesc };
                this.data_blog.Rows.Add(row);
            }

            this.webBrowser.ScriptErrorsSuppressed = true;
        }


        /// <summary>
        /// 创建右键菜单
        /// </summary>
        /// <returns></returns>
        private ContextMenuStrip CreateContextMenu()
        {
            System.Windows.Forms.ContextMenuStrip contextMenuStrip = new System.Windows.Forms.ContextMenuStrip();
            System.Windows.Forms.ToolStripMenuItem menu_1 = new System.Windows.Forms.ToolStripMenuItem();
            System.Windows.Forms.ToolStripMenuItem menu_2 = new System.Windows.Forms.ToolStripMenuItem();
            System.Windows.Forms.ToolStripMenuItem menu_3 = new System.Windows.Forms.ToolStripMenuItem();

            System.Windows.Forms.ToolStripSeparator toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
            // 
            // contextMenuStrip1
            // 
            contextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { menu_1, menu_2, menu_3, toolStripSeparator1 });
            contextMenuStrip.Name = "contextMenuStrip1";
            contextMenuStrip.Size = new System.Drawing.Size(153, 120);

            menu_1.Enabled = true;
            menu_1.Name = "new";
            menu_1.Size = new System.Drawing.Size(152, 22);
            menu_1.Text = "添加     ";

            menu_2.Enabled = false;
            menu_2.Name = "modify";
            menu_2.Size = new System.Drawing.Size(152, 22);
            menu_2.Text = "修改     ";

            menu_3.Enabled = false;
            menu_3.Name = "delete";
            menu_3.Size = new System.Drawing.Size(152, 22);
            menu_3.Text = "删除     ";


            return contextMenuStrip;
        }



        /// <summary>
        /// 写配置信息函数
        /// </summary>
        public void WriteConfigure()
        {

            List<Blog> list = new List<Blog>();
            foreach (DataGridViewRow row in this.data_blog.Rows)
            {
                if (row.Cells[Cblog.Btitle].Value != null && row.Cells[Cblog.Btitle].Value.ToString() != "")
                {
                    
                    Blog blog = new Blog();
                    blog.blogTitle = row.Cells[Cblog.Btitle].Value.ToString();
                    blog.blogUrl = row.Cells[Cblog.BUrl].Value.ToString();
                    blog.blogUsername = row.Cells[Cblog.BUsername].Value.ToString();
                    blog.blogPassowod = row.Cells[Cblog.BPassword].Value.ToString();
                    blog.blogType = row.Cells[Cblog.BType].Value.ToString();
                    blog.blogDesc = row.Cells[Cblog.BDesc].Value.ToString();
                    blog.blogKeyword = row.Cells[Cblog.BKeyword].Value.ToString();
                    list.Add(blog);
                }
            }
            
            //保存配置文件
            ConfigXML.Content = list;          
        }

        private void contextMenuStrip_Paint(object sender, PaintEventArgs e)
        {
            if (sender is System.Windows.Forms.ContextMenuStrip)
            {
                bool IsSelected = this.data_blog.SelectedRows.Count == 1 ? true : false;
                ContextMenuStrip contextMenuStrip = ((System.Windows.Forms.ContextMenuStrip)sender);
                foreach (ToolStripItem item in contextMenuStrip.Items)
                {
                    item.Enabled = (item.Name == "edit" || item.Name == "del") ? IsSelected : true;
                }
            }
        } 
     

        /// <summary>
        /// 右键菜单元素单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void contextMenuStrip_ItemClicked(object sender, System.Windows.Forms.ToolStripItemClickedEventArgs e)
        {
            try
            {
                DataGridViewRow row = null;
                if (this.data_blog.SelectedRows.Count == 1)
                {
                    row = this.data_blog.SelectedRows[0];
                }
                if ("new" == e.ClickedItem.Name)
                {
                    AddForm quickForm = new AddForm();
                    quickForm.ReturnHandler += new Action<Blog>(delegate(Blog b)
                    {
                        int index = this.data_blog.Rows.Add();
                        if (index > -1)
                        {
                            this.data_blog.Rows[index].Cells[Cblog.Btitle].Value = b.blogTitle;
                            this.data_blog.Rows[index].Cells[Cblog.BUrl].Value = b.blogUrl;
                            this.data_blog.Rows[index].Cells[Cblog.BUsername].Value = b.blogUsername;
                            this.data_blog.Rows[index].Cells[Cblog.BPassword].Value = b.blogPassowod;
                            this.data_blog.Rows[index].Cells[Cblog.BType].Value = b.blogType;
                            this.data_blog.Rows[index].Cells[Cblog.BDesc].Value = b.blogDesc;
                            this.data_blog.Rows[index].Cells[Cblog.BKeyword].Value = b.blogKeyword;

                        }
                        WriteConfigure();
                    });
                    quickForm.ShowDialog();
                }
                else if ("modify" == e.ClickedItem.Name)
                {
                    if (row != null)
                    {
                        AddForm quickForm = new AddForm();
                        Blog blog = new Blog(); 
                        blog.blogTitle = row.Cells[Cblog.Btitle].Value.ToString();
                        blog.blogUrl = row.Cells[Cblog.BUrl].Value.ToString();
                        blog.blogUsername = row.Cells[Cblog.BUsername].Value.ToString();
                        blog.blogPassowod = row.Cells[Cblog.BPassword].Value.ToString();
                        blog.blogType = row.Cells[Cblog.BType].Value.ToString();
                        blog.blogDesc = row.Cells[Cblog.BDesc].Value.ToString();
                        blog.blogKeyword = row.Cells[Cblog.BKeyword].Value.ToString(); 

                        quickForm.Content = blog;
                        quickForm.ReturnHandler += new Action<Blog>(delegate(Blog b)
                        {
                            row.Cells[Cblog.Btitle].Value = b.blogTitle;
                            row.Cells[Cblog.BUrl].Value = b.blogUrl;
                            row.Cells[Cblog.BUsername].Value = b.blogUsername;
                            row.Cells[Cblog.BPassword].Value = b.blogPassowod;
                            row.Cells[Cblog.BType].Value = b.blogType;

                            row.Cells[Cblog.BKeyword].Value = b.blogKeyword;

                            row.Cells[Cblog.BDesc].Value = b.blogDesc; 
                            WriteConfigure();
                        });

                        quickForm.ShowDialog();
                    }
                }
                else if ("delete" == e.ClickedItem.Name)
                {
                    if (row != null)
                    {
                        this.data_blog.Rows.RemoveAt(row.Index);
                        WriteConfigure();
                    }
                }

            }
            catch(Exception ex) {
                Console.WriteLine(ex.ToString());
            }
        }
        /// <summary>
        /// 点击查看按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void data_blog_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView DataGridView1 = (DataGridView)sender;
            if (e.ColumnIndex == 7)
            {
                string Password = DataGridView1.CurrentRow.Cells[Cblog.BPassword].Value.ToString();
                string Username = DataGridView1.CurrentRow.Cells[Cblog.BUsername].Value.ToString();
                string Url = DataGridView1.CurrentRow.Cells[Cblog.BUrl].Value.ToString();
                string type = DataGridView1.CurrentRow.Cells[Cblog.BType].Value.ToString();
                AutoLogin(Username, Password, type, Url);
                 
            } 
        }

        /// <summary>
        /// 转发自动登录的操作
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="type"></param>
        /// <param name="url"></param>
        private void AutoLogin(string username, string password, string type, string url)
        {
            tab_blog.SelectTab(1);
            this.password = password;
            this.username = username;
            this.url = url;
            this.type = type;
            this.count = 1;

            string outpixnet = "http://panel.pixnet.cc/logout";
            string outyahoo = "http://tw.rd.yahoo.com/referurl/hp/1024/pa/exit/*https://login.yahoo.com/config/login?&.srv=fpctx&logout=1&.direct=1&.done=http://tw.yahoo.com";
            string outyam = "http://member.yam.com/BOX/Logout.aspx?URL=http%3A//blog.yam.com/";
            string outblogger = "http://www.blogger.com/logout.g"; 
  
            if (type == "痞客邦")
            { 
                //首先执行以下登出操作
                webBrowser.Url = new Uri(outpixnet); 
                Thread.Sleep(2000);
                webBrowser.Navigate(new Blog().pkbUrl); 
            }
            else if (type == "yam")
            {
                webBrowser.Navigate(outyam);
                webBrowser.Url = new Uri(new Blog().yamUrl); 
            }
            else if (type == "blogger")
            {
                webBrowser.Navigate(outblogger);
                webBrowser.Url = new Uri(new Blog().bloggerUrl); 
            }
            else if (type == "WordPress")
            {
                webBrowser.Navigate(url + "?loggedout=true");
                webBrowser.Navigate(url);
            }
            else if (type == "Yahoo")
            {
                webBrowser.Navigate(outyahoo);
                webBrowser.Url = new Uri(new Blog().Yahoourl);
            }
            else
            {
                webBrowser.Url = new Uri(url);
            }
         
        }


 
  



        /// <summary>
        /// 登录痞客帮
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="url"></param>
        private void Loginpkb()
        {
            webBrowser.Document.GetElementById("input-username").InnerText = this.username;
            webBrowser.Document.GetElementById("input-password").InnerText = this.password;
            HtmlElement btn = webBrowser.Document.GetElementById("login-send");
            if (btn != null)
            {
                ///触发他的点击事件 
                btn.InvokeMember("click");
            }
        }


        /// <summary>
        /// 登录痞客帮
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="url"></param>
        private void LoginWordPress()
        {
            webBrowser.Document.GetElementById("user_login").InnerText = this.username;
            webBrowser.Document.GetElementById("user_pass").InnerText = this.password;
            HtmlElement btn = webBrowser.Document.GetElementById("wp-submit");
            if (btn != null)
            {
                ///触发他的点击事件 
                btn.InvokeMember("click");
            }
        }


        /// <summary>
        /// 登录痞客帮
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="url"></param>
        private void Loginyam()
        {

            webBrowser.Document.All["id"].InnerText = this.username;
            webBrowser.Document.All["pwd"].InnerText = this.password;

            HtmlElement btn = webBrowser.Document.GetElementById("somelogin");
            if (btn != null)
            {
                ///触发他的点击事件 
                btn.InvokeMember("submit");
            }

        }


        /// <summary>
        /// 登录痞客帮
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="url"></param>
        private void Loginblogger()
        {
            webBrowser.Document.GetElementById("Email").InnerText = this.username;
            webBrowser.Document.GetElementById("Passwd").InnerText = this.password;
            HtmlElement btn = webBrowser.Document.GetElementById("signIn");
            if (btn != null)
            {
                ///触发他的点击事件 
                btn.InvokeMember("click");
            }
        }

        /// <summary>
        /// 登录雅虎
        /// </summary>
        private void LoginYahoo()
        {
            webBrowser.Document.GetElementById("username").InnerText = this.username;
            webBrowser.Document.GetElementById("passwd").InnerText = this.password;
            HtmlElement btn = webBrowser.Document.GetElementById(".save");
            if (btn != null)
            {
                ///触发他的点击事件 
                btn.InvokeMember("click");
            }
        }

        private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        { 
            if (this.count == 1)
            {
                if (this.type == "痞客邦")
                {
                    Loginpkb();
                }
                else if (type == "yam")
                {
                    Loginyam();
                }
                else if (type == "blogger")
                {
                    Loginblogger();
                }
                else if (type == "WordPress")
                {
                    LoginWordPress();
                }
                else if (type == "Yahoo")
                {
                    LoginYahoo();
                }
                this.count++; 
            }

           
        }

        private void data_blog_MouseMove(object sender, MouseEventArgs e)
        {
            if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
            {
                // If the mouse moves outside the rectangle, start the drag.
                if (dragBoxFromMouseDown != Rectangle.Empty &&
                    !dragBoxFromMouseDown.Contains(e.X, e.Y))
                {

                    // Proceed with the drag and drop, passing in the list item.                   
                    DragDropEffects dropEffect = data_blog.DoDragDrop(
                   data_blog.Rows[rowIndexFromMouseDown],
                   DragDropEffects.Move);
                }
            }

        }

        private void data_blog_MouseDown(object sender, MouseEventArgs e)
        {
            // Get the index of the item the mouse is below.
            rowIndexFromMouseDown = data_blog.HitTest(e.X, e.Y).RowIndex;

            if (rowIndexFromMouseDown != -1)
            {
                // Remember the point where the mouse down occurred. 
                // The DragSize indicates the size that the mouse can move 
                // before a drag event should be started.               
                Size dragSize = SystemInformation.DragSize;

                // Create a rectangle using the DragSize, with the mouse position being
                // at the center of the rectangle.
                dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width / 2),
                                                               e.Y - (dragSize.Height / 2)),
                                   dragSize);
            }
            else
                // Reset the rectangle if the mouse is not over an item in the ListBox.
                dragBoxFromMouseDown = Rectangle.Empty;

        }

        private void data_blog_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;

        }

        private void data_blog_DragDrop(object sender, DragEventArgs e)
        {
          
            Point clientPoint = data_blog.PointToClient(new Point(e.X, e.Y));

          
            rowIndexOfItemUnderMouseToDrop =
                data_blog.HitTest(clientPoint.X, clientPoint.Y).RowIndex;

            
            if (e.Effect == DragDropEffects.Move)
            {
                DataGridViewRow rowToMove = e.Data.GetData(
                   typeof(DataGridViewRow)) as DataGridViewRow;
                data_blog.Rows.RemoveAt(rowIndexFromMouseDown);
                data_blog.Rows.Insert(rowIndexOfItemUnderMouseToDrop, rowToMove);
                WriteConfigure();

            }

        }
        /// <summary>
        /// 一鍵采集數據
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_gather_Click(object sender, EventArgs e)
        {
            txt_log.Text = "";
            GatherTask gt = new GatherTask("");
            gt.keyword = "";
            gt.Log += new GatherTask.LogHandle(this.Log);
            gt.ShowStop += new RuoTeng.Util.Task.TaskEventHandler(this.ShowStop);
            new System.Threading.Thread(delegate()
            {
                btn_gather.Enabled = false;
                gt.Start();
            }).Start();
        }



        private void Log(string log, System.Drawing.Color color)
        {
            this.txt_log.AppendText(log + System.Environment.NewLine);
            txt_log.ForeColor = color;
        }
        private void ShowStop(RuoTeng.Util.Task work)
        {
            btn_gather.Enabled = true;
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            if (txt_log.Text.Trim() != "")
            {

                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "TXT文件|*.txt";
                saveFileDialog.FilterIndex = 1;
                saveFileDialog.FileName = "痞客幫造訪结果文件";
                saveFileDialog.RestoreDirectory = true;
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string fName = saveFileDialog.FileName;
                    if (txt_log.Text.Trim() != "")
                    {
                        bool issave = RTFile.WriteFile(fName, txt_log.Text);

                        if (issave == true)
                        {

                            MessageBox.Show("文件保存成功");
                        }
                        else
                        {
                            MessageBox.Show("文件保存失败");
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("内容不能为空");

            }
        }
        /// <summary>
        /// 自动造访
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_visit_Click(object sender, EventArgs e)
        {
            MessageBox.Show("请确定已经登录一个账户");

            List<string> list = TextBoxTools.getTextBoxList(txt_log);

            this.visitcount = list.Count-1;
            this.timer1.Enabled = true;
            this.timer1.Tick+=new EventHandler(timer1_Tick);
            
            this.timer1.Start();
           

        }
        /// <summary>
        /// 自動造訪
        /// </summary>
        private void startVisit()
        {
            List<string> list = TextBoxTools.getTextBoxList(txt_log);
            string url = list[this.visitcount];

            this.webBrowser.Navigate(url);

            if (this.visitcount > 0 && this.visitcount != 0)
            {
                this.visitcount--;
            }
            if (this.visitcount < 0)
            {
                this.timer1.Enabled = false;
                this.timer1.Stop();
                MessageBox.Show("痞客幫自動造訪結束");
            }
        }

        /// <summary>
        /// 自動造訪yam
        /// </summary>
        private void startYam()
        {
            List<string> list = TextBoxTools.getTextBoxList(txt_yam);
            string url = list[this.visitcount];

            this.webBrowser.Navigate(url);

            if (this.visitcount >= 0 )
            {
                this.visitcount--;
            }
            if (this.visitcount < 0)
            {
                this.timer1.Enabled = false;
                this.timer1.Stop();
                MessageBox.Show("yam自動造訪結束");
            }

        }


         private void timer1_Tick(object sender, EventArgs e)
         {
             startVisit();
         }

         private void timer1_Tick2(object sender, EventArgs e)
         {
             startYam();
         }
        /// <summary>
        /// 采集yam
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
         private void btn_yamgather_Click(object sender, EventArgs e)
         {
             txt_yam.Text = "";

             string blogPattern = @"(?isx)<a\shref=.http://blog.yam.com/(?<content>\w*)\u0022";//博客地址 
             string result = Http.GetData("http://blog.yam.com/", null, Encoding.UTF8);
             MatchCollection matches = Regex.Matches(result, blogPattern);


             List<string> list = new List<string>();
            

             if (matches.Count > 0)
             {
                 
                 foreach (Match match in matches)
                 {
                     GroupCollection groups = match.Groups;
                     string title = groups["content"].ToString();
                     if (title.Trim() != ""&&list.Contains(title)==false)
                     {
                         list.Add(title);
                     }
                 }

             }

             foreach (string str in list)
             {
                 string url=string.Format("http://blog.yam.com/{0}",str);
                 txt_yam.AppendText(url+System.Environment.NewLine);
             }
         }

         private void btn_saveyam_Click(object sender, EventArgs e)
         {
             if (txt_yam.Text.Trim() != "")
             {

                 SaveFileDialog saveFileDialog = new SaveFileDialog();
                 saveFileDialog.Filter = "TXT文件|*.txt";
                 saveFileDialog.FilterIndex = 1;
                 saveFileDialog.FileName = "YAM造訪结果文件";
                 saveFileDialog.RestoreDirectory = true;
                 if (saveFileDialog.ShowDialog() == DialogResult.OK)
                 {
                     string fName = saveFileDialog.FileName;
                     if (txt_yam.Text.Trim() != "")
                     {
                         bool issave = RTFile.WriteFile(fName, txt_yam.Text);

                         if (issave == true)
                         {

                             MessageBox.Show("文件保存成功");
                         }
                         else
                         {
                             MessageBox.Show("文件保存失败");
                         }
                     }
                 }
             }
             else
             {
                 MessageBox.Show("内容不能为空");

             }
         }

         private void btn_yamvisit_Click(object sender, EventArgs e)
         {
             MessageBox.Show("请确定已经登录一个账户");

             List<string> list = TextBoxTools.getTextBoxList(txt_yam);

             this.visitcount = list.Count - 1;
             this.timer1.Enabled = true;
             this.timer1.Tick+=new EventHandler(timer1_Tick2);
             this.timer1.Start();
         }
    }
}
